<?php

namespace app\common\controller;

use app\common\library\token\TokenExpirationException;
use app\sysuser\library\Auth;
use ba\Exception;
use think\exception\ValidateException;
use think\facade\Event;
use think\Model;
use Throwable;

class SysBackend extends Api
{
    /**
     * 无需登录的方法，访问本控制器的此方法，无需管理员登录
     * @var array
     */
    protected array $noNeedLogin = [];

    /**
     * 无需鉴权的方法
     * @var array
     */
    protected array $noNeedPermission = [];

    /**
     * 新增/编辑时，对前端发送的字段进行排除（忽略不入库）
     * @var array|string
     */
    protected array|string $preExcludeFields = [];

    /**
     * 权限类实例
     * @var Auth
     */
    protected Auth $auth;

    /**
     * 模型对象
     * @var Model
     */
    protected $model;


    private static $tokenName = ['ba', 'sysuser', 'token'];

    /**
     * 初始化
     * @throws Throwable
     */
    public function initialize(): void
    {
        parent::initialize();

        $needLogin = !action_in_arr($this->noNeedLogin);


        try {
            // 初始化管理员鉴权实例
            $this->auth = Auth::instance();
            $token = get_auth_token(self::$tokenName);
            if ($token) {
                $res = $this->auth->init($token);
                if (!$res) {
                    throw new ValidateException($this->auth->getError());
                }
            }
        } catch (TokenExpirationException $e) {
            if ($needLogin) {
                $this->fail(__('Token expiration'), [], 409);
            }
        } catch (ValidateException $e) {
            if ($needLogin) {
                $this->fail($e->getMessage(), null, 409, self::SILENT);
            }
        } catch (Exception $e) {
            $this->fail($e->getMessage(), null, 409, self::SILENT);
        }
        if ($needLogin) {
            if (!$this->auth->isLogin()) {
                $this->fail(__('Please login first'), null, 303, self::SILENT);
            }
            // if (!action_in_arr($this->noNeedPermission)) {
            //     $routePath = ($this->app->request->controllerPath ?? '') . '/' . $this->request->action(true);
            //     if (!$this->auth->check($routePath)) {
            //         $this->error(__('You have no permission'), [], 401);
            //     }
            // }
        }
        // 管理员验权和登录标签位
        Event::trigger('backendInit', $this->auth);
    }

    public static function getTokenName()
    {
        return self::$tokenName;
    }
}